var chatPeer = require('../chatPeer');
module.exports.ready = function () {
  var defer = $.Deferred();
  chatExists(function (exists) {
    if (exists) {
      WebIMTabEvent.broadcast('chat.refresh', {target: Meta.chatId, type: Meta.type, clueId: Meta.clueId, search: location.search});
      document.write('');
      window.close();
      return;
    }

    WebIMTabEvent.broadcast('chat.created', {target: Meta.chatId, type: Meta.type, clueId: Meta.clueId, search: location.search});
    defer.resolve();
  });
  return defer;
};

module.exports.chatExists = chatExists;

var existsResTime = 0;
WebIMTabEvent.on('chat.exists', function () {
  existsResTime = new Date().getTime();
});

WebIMTabEvent.on('chat.isexists', function (data) {
  if (data.target || !window.IMDisconnected) {
    WebIMTabEvent.broadcast('chat.exists', data);
  }
});

// 收到刷新页面请求，询问用户是否刷新
WebIMTabEvent.on('chat.refresh', function (data) {
  console.log('chat.refresh', data);
  var leave = confirm('已存在聊天窗口，确定离开吗?');
  if (leave) {
    location.search = data.search;
  }
});

WebIMTabEvent.on('im.user.changed', function (data) {
  document.write('<span style="display: none">请关闭窗口</span>');
  alert('您已切换用户，窗口将关闭，请重新进入会话');
  window.close();
});

function chatExists(callback) {
  var requestTime = new Date().getTime();
  WebIMTabEvent.broadcast('chat.isexists', {target: Meta.target, search: location.search});
  setTimeout(function () {
    callback(existsResTime >= requestTime);
  }, 500);
}
